package com.amado.easyui2.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.amado.easyui2.constant.GlobalConstants;

public class UserLoginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setHeader("Content-type", "text/html;charset=UTF-8");
		String method = req.getParameter("method");
		if ("login".equals(method)) {
			login(req, resp);
		} else if ("loginOut".equals(method)) {
			loginOut(req, resp);
		}
	}

	private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName = req.getParameter("userName");
		String password = req.getParameter("password");
		// verifyCode 验证码verifyCode
		String verifyCode = req.getParameter("verifyCode");
		String sessionVerifyCode = (String) req.getSession(false).getAttribute("verifyCode");
		if(sessionVerifyCode == null || !sessionVerifyCode.equals(verifyCode)) {
			req.setAttribute("msg", "验证码错误");
			req.getRequestDispatcher("login.jsp").forward(req, resp);
			return;
		}
		if ("admin".equals(userName) && "123456".equals(password)) {
			req.getSession().setAttribute(GlobalConstants.SESSION_USER, userName);
			resp.sendRedirect("index.jsp");
		} else {
			req.setAttribute("msg", "用户名或密码错误");
			req.getRequestDispatcher("login.jsp").forward(req, resp);
		}
	}
	private void loginOut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.getSession().removeAttribute(GlobalConstants.SESSION_USER);//注销
		resp.sendRedirect("login.jsp");
	}
}
